package com.xiaoning.sun.spring.mvc.utils;

import java.lang.reflect.Field;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.xiaoning.sun.spring.mvc.annotation.ValidatorAnnotation;
import com.xiaoning.sun.spring.mvc.model.RegisterForm;

public class FieldValidator {

	public static void validator(Object object, Errors errors){
		Class<? extends Object> clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field: fields){
			fieldValidation(field, object, errors);
		}
	}
	
	public static void fieldValidation(Field field, Object object, Errors errors){
		try {
			field.setAccessible(true);
			Object value = field.get(object);
			ValidatorAnnotation validatorAnnotation = field.getAnnotation(ValidatorAnnotation.class);
			if(null != validatorAnnotation){
				if(validatorAnnotation.notNullAble() && StringUtils.isEmpty(value.toString())){
					ValidationUtils.rejectIfEmptyOrWhitespace(errors, field.getName(), validatorAnnotation.propertyKey(), validatorAnnotation.defaultAlertMessage());
					return;
				}
				if(!StringUtils.isEmpty(value.toString()) && !StringUtils.isEmpty(validatorAnnotation.regexExpression())){
					if(!value.toString().matches(validatorAnnotation.regexExpression())){
						errors.rejectValue(field.getName(), "", validatorAnnotation.description());
						return;
					}
				}
			}
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			field.setAccessible(false);
		}
	}
	
	public  static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
		RegisterForm registerForm = new RegisterForm();
		registerForm.setUserName("user name");
		FieldValidator.validator(registerForm, null);
	}
}
